<?php
namespace App\Service\Admin\Erqi;

class CheapService extends BaseService
{
    //限时折扣

    /**
     * 列表
     */
    public function getList()
    {
        $db = $this->dbConn($this->dbCheap)->where('del', 0);
        $total = $db->count();
        $res = $db->get();
        if (!count($res)) {
            return $this->toback(-2, '没有记录');
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $gOne = (array) $this->dbConn($this->dbGoods)
                ->where('id', $v['gid'])
                ->first();
            $arys[] = [
                'id' => $v['id'],
                'gid' => $v['id'],
                'gname' => empty($gOne) ? '-' : $gOne['title'],
                'per' => $v['per'],
                'start_time' => $v['start_time'],
                'end_time' => $v['end_time'],
                'period' => $v['start_time'].'至'.$v['end_time'],
                'addtime' => $v['addtime'],
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }

    /**
     * 添加
     * @param string $gno 商品编号
     * @param array $pas
     */
    public function add($gno, $pas)
    {
        $gOne = (array) $this->dbConn($this->dbGoods)
            ->where('gno', $gno)
            ->first();
        if (empty($gOne)) {
            return $this->toback(-2, '没有商品');
        }
        $this->dbConn($this->dbCheap)->where('gid', $gOne['id'])
            ->update(['del' => 1, 'deltime' => toDate()]);
        $pas['gid'] = $gOne['id'];
        $pas['addtime'] = toDate();
        $lastid = $this->dbConn($this->dbCheap)->insertGetId($pas);
        if (!$lastid) {
            return $this->toback(-1, '添加失败');
        }
        return $this->toback();
    }

    /**
     * 删除
     * @param int $id
     */
    public function setDel($id)
    {
        $up = $this->dbConn($this->dbCheap)->where('id', $id)
            ->update(['del' => 1, 'deltime' => toDate()]);
        if (!$up) {
            return $this->toback(-1, '删除失败');
        }
        return $this->toback();
    }
}